#include "DownloadedFile.h"
#include <ext/stdio_sync_filebuf.h>

using namespace std;

DownloadedFile::DownloadedFile(string fileName) {
	this->fileName = fileName;

	this->fd = open(this->fileName.c_str(), O_CREAT | O_RDWR, S_IWRITE | S_IREAD);

	this->fl.l_type = F_WRLCK;
	this->fl.l_whence = SEEK_SET;
	this->fl.l_start = 0;
	this->fl.l_len = 0;
	this->fl.l_pid = getpid ();
}

DownloadedFile::~DownloadedFile() {
	close(this->fd);
}

int DownloadedFile::writeData(char* data, int dataSize) {
	lseek ( this->fd,0,SEEK_END );
	int result = write(this->fd, (const void *)data, dataSize);
	return result;
}

int DownloadedFile::readData(char* buffer, int buffSize) {
	int result = read(this->fd, (void *)buffer, buffSize);
	return result;
}

int DownloadedFile::getWriteLock () {
	this->fl.l_type = F_WRLCK;
	int result = fcntl(this->fd, F_SETLKW, &(this->fl));
	return result;
}

int DownloadedFile::getReadLock () {
	this->fl.l_type = F_RDLCK;
	int result = fcntl(this->fd, F_SETLKW, &(this->fl));
	return result;
}

int DownloadedFile::unlock () {
	this->fl.l_type = F_UNLCK;
	int result = fcntl(this->fd, F_SETLK, &(this->fl));
	return result;
}
